/**   
* @Title: JarUtils.java 
* @Package cn.com.ytst.data.integration.util 
* @Description:
* @author 123774135@qq.com 
* @date 2019年8月7日 下午4:04:54 
* @version V1.0   
*/
package cn.com.ytst.data.integration.util;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ytst.framework.common.exception.BusinessException;

import sun.misc.ClassLoaderUtil;

/**
 * @ClassName: JarUtils
 * @Description:
 * @author 123774135@qq.com
 * @date 2019年8月7日 下午4:04:54
 * 
 */
public class JarUtils {

	private static Logger logger = LoggerFactory.getLogger(JarUtils.class);

	/**
	 * 
	 * @Title: loadJar 
	 * @Description: 
	 * @param jarPath 
	 * @param  classname 类名一般是包名+类名  
	 * @param methodName  方法名称，
	 * @param parameterTypes 方法里面的参数类型
	 * @param constructor  构造函数
	 * @param value 传入的值
	 * @return Object
	 * 返回类型 @throws
	 */
	@SuppressWarnings("restriction")
	public static Object loadJar(String jarPath, String classname, String methodName, Class<?>[] parameterTypes,
			Class<?>  constructor,Object ... value) {
		Class<?> clazz = null;
		URLClassLoader urlClassLoader = null;
		try {
			urlClassLoader = new URLClassLoader(new URL[] { new URL("file:" + jarPath) });
			clazz = urlClassLoader.loadClass(classname);
			Method method = clazz.getMethod(methodName, parameterTypes);
			Object object = null;
			if(null != constructor) {
				//说明该类有构造函数
				Class<?> [] classes = new Class[]{constructor};
				object = clazz.getConstructor(classes ).newInstance();
			}else {
				object = clazz.newInstance();
			}
			Object [] prarms = null;
			if(null != value) {
				prarms = value;
			}else {
				prarms = new Object[]{null};
			}
			return method.invoke(object,prarms);
		} catch (Exception e) {
			logger.error("",e);
			throw new BusinessException(Constants.ERROR, e);
		}finally {
			if(null != urlClassLoader) {
				ClassLoaderUtil.releaseLoader(urlClassLoader);//进行资源释放
			}
			
		}

	}
	public static void main(String[] args) {
		String result = (String) JarUtils.loadJar("D:\\.m2\\commons-lang\\commons-lang\\2.6\\commons-lang-2.6.jar", "org.apache.commons.lang.StringUtils", "trimToEmpty", new Class[] {String.class}, null, "123456");
		System.out.println("----"+result);
	}

}
